#!/bin/bash

set -e

VERSION=$1

# 步骤1：如果Kubernetes仓库文件不存在，则创建它
REPO_FILE=/etc/yum.repos.d/kubernetes.repo
if [ ! -f "$REPO_FILE" ]; then
    cat <<EOF > "$REPO_FILE"
[kubernetes]
name=Kubernetes
baseurl=https://mirrors.aliyun.com/kubernetes/yum/repos/kubernetes-el7-x86_64/
enabled=1
gpgcheck=1
repo_gpgcheck=1
gpgkey=https://mirrors.aliyun.com/kubernetes/yum/doc/yum-key.gpg https://mirrors.aliyun.com/kubernetes/yum/doc/rpm-package-key.gpg
EOF
    echo "已添加 Kubernetes 仓库。"
else
    echo "Kubernetes 仓库已存在。"
fi

# 步骤2：如果未安装所需的软件包，则进行安装
REQUIRED_PACKAGES=kubectl-$VERSION
if ! rpm -q "$REQUIRED_PACKAGES" > /dev/null 2>&1; then
    yum install -y "$REQUIRED_PACKAGES"
    echo "已安装 $REQUIRED_PACKAGES。"
else
    echo "$REQUIRED_PACKAGES 已安装。"
fi

# 步骤3：如果存在bash补全脚本，则进行源化
BASH_COMPLETION_SCRIPT=/etc/profile.d/bash_completion.sh
if [ -f "$BASH_COMPLETION_SCRIPT" ]; then
    source "$BASH_COMPLETION_SCRIPT"
    echo "已源化bash补全脚本。"
else
    echo "未找到bash补全脚本。"
fi

# 步骤4：如果 .bashrc 中未添加 kubectl 补全，则进行添加
BASHRC_FILE=~/.bashrc
if ! grep -q "source <(kubectl completion bash)" "$BASHRC_FILE"; then
    echo "source <(kubectl completion bash)" >> "$BASHRC_FILE"
    source "$BASHRC_FILE"
    echo "已将 kubectl 补全添加到 .bashrc。"
else
    echo "kubectl 补全已添加到 .bashrc。"
fi

if [ ! -d "~/.kube" ]; then
    mkdir ~/.kube
    echo "输入 k8s-master 的 IP 地址："
    read IP
    scp root@$IP:/etc/kubernetes/admin.conf ~/.kube/config
else
    rm -rf  ~/.kube
    mkdir -p ~/.kube
    echo "输入 k8s-master 的 IP 地址："
    read IP
    scp root@$IP:/etc/kubernetes/admin.conf ~/.kube/config
fi